package com.hxx.widget.richtext.views

import android.content.Context
import android.text.Selection
import android.text.style.ParagraphStyle
import android.util.AttributeSet
import android.view.KeyEvent
import androidx.appcompat.widget.AppCompatEditText

class RichEditTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatEditText(context, attrs, defStyleAttr) {
    private var call: (Int, Int) -> Unit = { _, _ -> }
    private var deleteAction: () -> Unit = {}
    override fun onSelectionChanged(selStart: Int, selEnd: Int) {
        super.onSelectionChanged(selStart, selEnd)
        call?.invoke(selStart, selEnd)
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_DEL && event?.action == KeyEvent.ACTION_DOWN) {
            val selectionStart = Selection.getSelectionStart(text)
            if (selectionStart == 0) {
                val numberSpans = text?.getSpans(0,0,NumberBulletSpan::class.java)
                numberSpans?.forEach {
                    text?.removeSpan(it)
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 键盘删除按键监听
     */
    fun addDeleteActionListener(deleteAction: () -> Unit) {
        this.deleteAction = deleteAction
    }

    /**
     * 光标位置变化监听
     */
    fun addSelectionListener(callback: (Int, Int) -> Unit) {
        this.call = callback
    }
}